const path = require('path')
const fs = require('fs')
const vm = require('vm')


function Module(id) {
    this.id = id;
    this.exports = {}
}
Module.wrapper = [
    `(function(module,exports,require,__filename,__dirname){`
    ,
    `})`
]
Module.extensions = {
    '.js'(module) {
        const script = fs.readFileSync(module.id, 'utf8');
        const fnStr = Module.wrapper[0] + script + Module.wrapper[1];
        // 提供一个沙箱环境不会污染其它变量
        const fn = vm.runInThisContext(fnStr)
        console.log(this) // { '.js': [Function: .js], '.json': [Function: .json] }
        console.log(Module)
        console.log(module) // Module { id: 'c:\\develop\\node\\nodebase\\a.js', exports: {} }
        fn.call(module.exports, module, module.exports, req, module.id, path.dirname(module.id));
    },
    '.json'(module) {
        const script = fs.readFileSync(module.id, 'utf8');
        // 转换成对象
        module.exports = JSON.parse(script)
    }
}
Module.resolveFileName = function (filename) {
    // 获取到绝对路径
    const absPath = path.resolve(__dirname, filename)
    console.log(absPath)
    // 判断文件是否存在
    const flag = fs.existsSync(absPath)
    let current = absPath;
    if (!flag) {
        const keys = Object.keys(Module.extensions);
        for (let i = 0; i < keys.length; i++) {
            current = absPath + keys[i];
            const flg = fs.existsSync(current);
            if (flg) {
                break;
            } else {
                current = null;
            }
        }
    }
    if (!current) {
        throw new Error('文件不存在')
    }
    return current
}
Module.prototype.load = function () {
    // 模块加载就是读取文件的内容
    const ext = path.extname(this.id);
    // 根据后缀调用不同的方法
    Module.extensions[ext](this)

}
Module._cache = {};
function req(filename) {
    const current = Module.resolveFileName(filename)
    console.log(current)
    // 缓存第一次引入的结果，有相同的引入直接返回结果
    if (Module._cache[current]) {
        return Module._cache[current].exports
    }
    const module = new Module(current)
    Module._cache[current] = module
    module.load()
    return module.exports;
}

let result = req('./a.js')
result = req('./a.js')

console.log(result)


const arr = [
    { name: 'zs', age:18},
    { name: 'zs', age:19},
    { name: 'szs', age:17},
    { name: 'zs', age:16},
    { name: 'zs', age:17},
]

const { log } = console

log(arr.find(item=>item.age===17))